<?php


namespace app\admin\traits;


use think\facade\View;
use think\response\Json;

Trait  ControllerTrait
{
    protected $m;   //当前控制器关联模型
    protected $v;   //当前控制器关联验证类

    /**通用首页
     * @return mixed
     * @throws \Exception
     */
    public function index()
    {
        return View::fetch();
    }

    /**通用添加数据
     * @return mixed|Response
     * @throws \Exception
     */
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if ($this->v && !$this->v->scene('add')->check($data)) {
                return xjson(404, $this->v->getError());
            }
            $result = $this->m->create($data);
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '添加失败！');
            }
        }
        return View::fetch();
    }

    /**
     * 通用编辑数据
     * @param $id
     * @return mixed|Response
     * @throws \Exception
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->v && !$this->v->scene('edit')->check($data)) {
                return xjson(404, $this->v->getError());
            }
            $this->m = $this->m->find($id);
            $result = $this->m->save($data);
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '修改失败!');
            }
        } else {
            $data = $this->m->find($id);
            View::assign('data', $data);
            return View::fetch();
        }
    }

    /**
     * ajax更新部分数据
     * @param $id
     * @return Response|Json
     */
    public function ajax($id)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->v && !$this->v->scene('ajax')->check($data)) {
                return json(['code' => 404, 'msg' => $this->v->getError(), 'data' => null]);
            }
            $m = $this->m->find($id);
            $m[key($data)] = $m[key($data)] ? 0 : 1;
            $result = $m->save();
            if ($result) {
                return xjson();
            } else {
                return xjson(404, '修改失败！');
            }
        } else {
            return xjson(403, '请求不被允许');
        }
    }

    /**
     * 通用删除
     * @param $id
     * @return Json
     */
    public function delete($id)
    {
        if (request()->isPost()) {
            $result = $this->m->where('id','in',$id)->delete();
            if ($result) {
                return xjson( '删除成功！');
            } else {
                return xjson(404, '删除失败！');
            }
        }
    }
}